package com.zige.zige.activity.videoplay;

import android.annotation.SuppressLint;
import android.app.AlertDialog.Builder;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zige.zige.R;
import com.zige.zige.activity.BaseActivity;
import com.zige.zige.constants.Constants;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.dialog.PromptDialog;
import com.zige.zige.dialog.ZiGeShareDialog;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.pojo.VideoInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.LogUtils;
import com.zige.zige.utils.PreferencesUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.view.Controller;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class PlayerAvtivity extends BaseActivity {

    ImageView img_loading;

    MediaPlayer mPlayer;
    SurfaceView mSurfaceView;
    Controller mController;
    OnClickListener next, prev, paul;
    SurfaceHolder.Callback mCallback;
    MediaPlayer.OnPreparedListener mPreparedListener;
    Controller.ControlOper mPlayerControl;
    ArrayList<VideoInfo> playList;
    //	VideoInfo[] infoArry;
    private long mExitTime = 0;
    int currentPosition = 0;


    private UserInfo userInfo;
    private int isPraises;

    private int recLen = 0;
    private boolean isShow = true;

    private OnClickListener zan, share;

    private String videoTitle, videoContext, videoImageUrl, jxVideoId;
    private String mVideoUrl;
    private AnimationDrawable animationDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        setContentView(R.layout.activity_videoplay);
        userInfo = application.getUserInfo();
        mPlayer = new MediaPlayer();
        mController = new Controller(PlayerAvtivity.this);
        initlistener();
        initSerface();
        screenState();
        mController.setPrevNextListeners(next, prev, null, zan, share);
        alert = new Builder(this);
        MyAsync task = new MyAsync();
        task.execute(getIntent());

    }

    private void initSerface() {
        img_loading = serchViewById(R.id.img_loading);
        img_loading.setBackgroundResource(R.drawable.being_loaded);
        animationDrawable = (AnimationDrawable) img_loading.getBackground();
        initListeners();
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        mSurfaceView.setVisibility(View.GONE);
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        surfaceHolder.addCallback(mCallback);
        animationDrawable = (AnimationDrawable) img_loading.getDrawable();
        animationDrawable.start();

    }


    private void playVideo(String videourl, String vid) {
        if (application.isLogin()) {
            mController.vid = vid;
        }
        try {
            mPlayer.reset();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(this, Uri.parse(videourl));
            mPlayer.setOnPreparedListener(mPreparedListener);
            mPlayer.prepareAsync();
            if( mPlayer.isPlaying()){
                closeLoadingDialog();
                animationDrawable.stop();
            }

            mPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    LogUtils.i(percent + "");
                    if (percent <= 100 && percent > 0)
                        mSurfaceView.setVisibility(View.VISIBLE);
                }
            });
            mPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (!finish) {
                        onNext();
                    }
                }
            });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    void onNext() {
        if (currentPosition >= playList.size() - 1) {
             showErrorDialog( "后面没有啦");
            return;
        }
        currentPosition++;
        getVideoDetils(String.valueOf(playList.get(currentPosition).getId()));
    }

    void initlistener() {
        next = new OnClickListener() {
            @Override
            public void onClick(View v) {
                onNext();
            }
        };
        prev = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (playList.get(currentPosition - 1).getType() == 0) {
                    ToastUtils.showToast(mContext, "前面没有了");
                    return;
                } else {
                    if (currentPosition <= 0) {
                         showErrorDialog( "前面没有啦");
                        return;
                    }
                    currentPosition--;
                    getVideoDetils(String.valueOf(playList.get(currentPosition).getId()));
                }
            }
        };
        zan = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (application.isLogin()) {
                    setPressPraise(operate);
                } else {
                    PromptDialog dialog = new PromptDialog();
                    dialog.show(getFragmentManager(), "dialo");

                }
            }
        };
        share = new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayer.pause();
                mPlayerControl.pause();
                sharesina();

            }
        };

    }

    String shareImageUrl;
    private void getVideoDetils(String vid) {
        String uid;
        if (application.isLogin()) {
            uid = application.getUserInfo().userID;
        } else {
            uid = "";
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("vid", vid);
        params.put("userId", uid);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, PlayerAvtivity.this, UrlConsts.VIDEO_DETILS) {
            @Override
            protected void handleResponse(String response) {
                Log.e("wu","普通食品   "+response);
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        object = object.getJSONObject("jxVideo");
                        jxVideoId = object.getString("id");
                        videoTitle = object.getString("videoName");
                        videoImageUrl = object.getString("videoPicUrl");
                        mVideoUrl = object.getString("videoUrl");
                        shareImageUrl = object.getString("sharePicUrl");
                        isPraises = object.getInt("praised");
                        playVideo(mVideoUrl, jxVideoId);
                        if (application.isLogin()) {
                            if (isPraises==1) {
                                Log.e("wu","MMMMM　　　"+isPraises);
                                operate = 1;
                                mController.zanSelect(R.drawable.videoplay_press_zan);
                            } else {
                                operate = 0;
                                mController.zanNormal();
                            }
                        } else {
                            mController.zanNormal();
                        }
                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    closeLoadingDialog();
                } finally {
                    closeLoadingDialog();
                }
            }

            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
            }
        });
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void screenState() {
        KeyguardManager mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
        boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
        if (flag) {
            return;
        } else {
            mPlayerControl.pause();
        }
    }
    int operate;

    private void setPressPraise(final int operated) {
        String deviceId = SystemUtils.getDeviceKey(PlayerAvtivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", deviceId);
        params.put("uid", application.getUserInfo().userID);
        params.put("account", application.getUserInfo().phoneNumber);
        params.put("jxVideoId", jxVideoId);
        params.put("operate", String.valueOf(operated));
        TaskExecutor.getInstance().execute(new PostRequestTask(params, PlayerAvtivity.this, UrlConsts.VIDEO_PRAISE) {
            @Override
            protected void handleError() {
                super.handleError();
                showLoadingDialog();
            }
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        closeLoadingDialog();
                        if (operated == 0) {
                            mController.zanSelect(R.drawable.videoplay_press_zan);
                            operate = 1;
                        }
                        if (operated == 1) {
                            mController.zanNormal();
                            operate = 0;
                        }

                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    closeLoadingDialog();
                     showErrorDialog( e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
//                    closeSpotsDialog();
                }
            }
        });
    }

    private void userWatchRecord(String videoId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("uid", application.getUserInfo().userID);
        params.put("videoId", videoId);
        TaskExecutor.getInstance().execute(new PostRequestTask(params, PlayerAvtivity.this, UrlConsts.USER_WATCH_RECORD) {
            @Override
            protected void handleResponse(String response) {

            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        animationDrawable.start();
    }

    @Override
    protected void onResume() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onResume();
    }

    @Override
    protected void onStop() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onStop();
    }

    class MyAsync extends AsyncTask<Intent, Integer, String> {

        @Override
        protected String doInBackground(Intent... params) {
            Intent intent = params[0];
            playList = (ArrayList<VideoInfo>) intent.getSerializableExtra("playList");
            currentPosition = intent.getIntExtra("position", 0);
            if (playList == null || playList.size() < 1) {
                 showErrorDialog( "无视频数据");
                finish();
            }
            registerReceiver();
            publishProgress(100);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (100 == values[0])
//				play(playList.get(currentPosition));
                getVideoDetils(playList.get(currentPosition).getId());
            super.onProgressUpdate(values);
        }

    }

    private void releaseMediaController() {

        mController.removeHandlerCallback();
        releaseMediaPlayer();
        mController = null;
    }

    private void releaseMediaPlayer() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);

        mController.show();

        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaController();
        unregisterReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayerControl.pause();
    }

    boolean finish = false;

    @Override
    public void onBackPressed() {
        finish = true;
        finish();
    }

    private void initListeners() {

        mCallback = new SurfaceHolder.Callback() {

            public void surfaceCreated(SurfaceHolder holder) {
                mPlayer.setDisplay(holder);
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        };

        mPreparedListener = new MediaPlayer.OnPreparedListener() {

            @SuppressLint("NewApi")
            public void onPrepared(MediaPlayer mp) {

                mController.setMediaPlayer(mPlayerControl);
                mController.setAnchorView((FrameLayout) findViewById(R.id.surfacecontainer));
                mPlayer.start();
                int h = mPlayer.getVideoHeight();
                int w = mPlayer.getVideoWidth();

                DisplayMetrics dm = getResources().getDisplayMetrics();
                int screenWidth = dm.widthPixels;
                int screenHeight = dm.heightPixels;
                if (w > screenWidth || h > screenHeight) {
                    // 计算出宽高的倍数
                    float vWidth = (float) w / (float) screenWidth;
                    float vHeight = (float) h / (float) screenHeight;
                    // 获取最大的倍数值，按大数值进行缩放
                    float max = Math.max(vWidth, vHeight);
                    // 计算出缩放大小,取接近的正值
                    w = (int) Math.ceil((float) w / max);
                    h = (int) Math.ceil((float) h / max);
                } else {
                    // 计算出宽高的倍数
                    float vWidth = (float) screenWidth / (float) w;
                    float vHeight = (float) screenHeight / (float) h;
                    // 获取最大的倍数值，按大数值进行缩放
                    float min = Math.min(vWidth, vHeight);
                    // 计算出缩放大小,取接近的正值
                    w = (int) Math.ceil((float) w * min);
                    h = (int) Math.ceil((float) h * min);
                }
                LogUtils.i("screen_h=" + screenHeight + "  screen_w=" + screenWidth);
                LogUtils.i("video_h=" + h + "  video_w=" + w);
                // 设置SurfaceView的大小并居中显示
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(w, h);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
//				if (currentVideo.getVideoTypeId() != 1)
//					mSurfaceView.setLayoutParams(layoutParams);
//				findViewById(R.id.surface_back).setBackgroundColor(Color.BLACK);

//				String backText = currentVideo.getVideoName();
                mController.setBackText(videoTitle);
                mController.hideScreen();
                mController.zanHidet();


            }
        };

        mPlayerControl = new Controller.ControlOper() {

            public void start() {
                mPlayer.start();
            }

            public void pause() {
                mPlayer.pause();
            }

            public int getDuration() {
                return mPlayer.getDuration();
            }

            public int getCurPosition() {
                return mPlayer.getCurrentPosition();
            }

            public void seekTo(int pos) {
                mPlayer.seekTo(pos);
            }

            public boolean isPlaying() {
                return mPlayer.isPlaying();
            }

            public int getBufPercent() {
                return 0;
            }

            public boolean canPause() {
                return true;
            }

            public boolean canSeekBackward() {
                return true;
            }

            public boolean canSeekForward() {
                return true;
            }

            public boolean isFullScreen() {
                return false;
            }

            @Override
            public void showTitle() {

            }

            @Override
            public void hiteTitle() {

            }

            public void fullScreen() {

            }
        };
    }

    NetworkStateChangedReceiver myReceiver;

    private void registerReceiver() {
        boolean isWifiOnly = PreferencesUtils.getBoolean(this, Constants.PREFERENCE_KEY_IS_WIFI_ONLY);
        boolean on = (boolean) SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.gesture_toggle, false);
        if (isWifiOnly) {
            return;
        }
        if (on == true) {
            return;
        }
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new NetworkStateChangedReceiver();
        this.registerReceiver(myReceiver, filter);


    }

    private void unregisterReceiver() {
        if (myReceiver != null) {
            this.unregisterReceiver(myReceiver);
            myReceiver = null;
        }
    }

    Builder alert;

    class NetworkStateChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
                ToastUtils.showToast(context, "网络不可以用");
                // 改变背景或者 处理网络的全局变量
            } else if (!wifiNetInfo.isConnected()) {
                mPlayerControl.pause();
                mPlayer.pause();
                Builder alert = new Builder(context);
                alert.setCancelable(false);
                alert.setTitle("提示");
                alert.setMessage("您正在使用非WIFI网络，播放将产生流量费用");
                alert.setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPlayerControl.start();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).show();
            }

        }

    }

    private UMImage shareVideoImageUrl,sinaImageUrl;
    private String shareVideoUrl;
    private void sharesina() {
        ZiGeShareDialog dialog = new ZiGeShareDialog();
        dialog.setSharelister(zigeshareLister);
        dialog.show(getFragmentManager(), "dialog");

        if (TextUtils.isEmpty(videoTitle)) {
            videoTitle = "VR小伴马";
        }

        shareVideoUrl = UrlConsts.SHARE_VIDEIO_URL + jxVideoId;
        shareVideoImageUrl = new UMImage(PlayerAvtivity.this, videoImageUrl);
        sinaImageUrl = new UMImage(PlayerAvtivity.this, shareImageUrl);
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            Toast.makeText(PlayerAvtivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(PlayerAvtivity.this," 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(PlayerAvtivity.this," 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    private ZiGeShareDialog.ZigeshareLister zigeshareLister = new ZiGeShareDialog.ZigeshareLister() {
        @Override
        public void shareSina() {
            new ShareAction(PlayerAvtivity.this).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(sinaImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXin() {
            new ShareAction(PlayerAvtivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXinCircle() {
            new ShareAction(PlayerAvtivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
